﻿using System;
using System.ComponentModel;

namespace Ferpect.ComponentModel
{
    internal class Site : ISite
    {
        private IComponent component;
        private Container container;
        private string name;
        private IServiceProvider serviceProvider;

        public Site(IComponent component, Container container, IServiceProvider serviceProvider)
        {
            if (component == null) throw new ArgumentNullException("component");
            if (container == null) throw new ArgumentNullException("container");

            this.component = component;
            this.container = container;
            this.serviceProvider = serviceProvider;
        }

        #region ISite Members

        public IComponent Component
        {
            get { return this.component; }
        }

        public IContainer Container
        {
            get { return this.container; }
        }

        public bool DesignMode
        {
            get { return false; }
        }

        public string Name
        {
            get
            {
                return this.name;
            }
            set
            {
                if (this.container.ComponentDictionary.ContainsKey(value))
                {
                    throw new ArgumentException("A component with this name already exists in the container.", "value");
                }
                if (this.name != value && this.name != null && this.container.ComponentDictionary.ContainsKey(this.name))
                {
                    this.container.ComponentDictionary.Remove(this.name);
                    this.container.ComponentDictionary.Add(value, this.component);
                }
                this.name = value;
            }
        }

        #endregion

        #region IServiceProvider Members

        public object GetService(Type serviceType)
        {
            if (serviceType == typeof(ISite))
            {
                return this;
            }
            if (this.serviceProvider != null)
            {
                return this.serviceProvider.GetService(serviceType);
            }
            return null;
        }

        #endregion
    }
}
